// pages/write/write.js
var { formatTime } = require('../../utils/Time')
const Multipart = require('../../utils/Multipart.min.js')
Page({
  data: {
    mn1: true,
    imglist: [],
    isShow: false,
    mesValue: '',
    userId: null,
    qtype: 0,
    casArray: ['点击选择', '表白墙', '许愿', '失物招领'],
    aabase: []
  },

  // 监听消息事件
  onMessage(data) {
    if (getApp().globalData.wdxx > 0) {
      wx.setTabBarBadge({
        index: 3, //从左边开始第几个页面显示
        text: '' + getApp().globalData.wdxx //消息条数
      })
    } else {
      wx.removeTabBarBadge({
        index: 3
      })
    }
  },

  /*发表按钮是否变颜色的判断*/
  gaibian: function (e) {
    let self = this
    if (e.detail.value != '') {
      this.setData({
        mn1: false
      })
    } else {
      this.setData({
        mn1: true
      })
    }
  },
  /*实现图片放大预览的js代码*/
  preview(event) {
    let index = event.currentTarget.dataset.index
    wx.previewImage({
      current: this.data.imglist[index], // 当前显示图片的http链接
      urls: this.data.imglist // 需要预览的图片http链接列表
    })
  },
  /*实现将相册或者照相的图片显示出来*/
  img_w_show() {
    var _this = this
    wx.chooseImage({
      count: 9, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var tempFilePaths = res.tempFilePaths
        
        _this.setData(
          {
            imglist: _this.data.imglist.concat(tempFilePaths)
          },
          () => {
            let imglist = _this.data.imglist
            // imglist.length = imglist.length
            console.log(imglist)
            if (imglist.length > 0) {
              _this.setData({
                mn1: false
              })
            } else {
              _this.setData({
                mn1: true
              })
            }
          }
        )
      },
      fail: function (error) {
        console.error('调用本地相册文件时出错')
        console.warn(error)
      },
      complete: function () {}
    })
  },
  /*图片右上角删除按钮功能的实现*/
  deleteImage: function (e) {
    let self = this
    let index = e.target.dataset.index
    let imglist = self.data.imglist
    imglist.splice(
      index,
      1
    ) /*splice() 方法向/从数组添加/删除项目，并返回删除的项目。
        注释：splice() 方法会改变原始数组。*/
    this.setData({
      imglist: imglist
    })
    imglist.length = imglist.length + 1
    imglist.length = imglist.length - 1
    if (imglist.length <= 0 && this.data.mesValue == '') {
      this.setData({
        mn1: true
      })
    }
  },
  onLoad(options) {
    const userId = wx.getStorageSync('userId')
    if (this.data.userId === null) {
      this.setData({
        userId
      })
    }
  },
  onShow() {
    this.setData({
      qtype: getApp().globalData.qtype
    })
    // 设置未读消息条数
    if (getApp().globalData.wdxx > 0) {
      wx.setTabBarBadge({
        index: 3, //从左边开始第几个页面显示
        text: '' + getApp().globalData.wdxx //消息条数
      })
    } else {
      wx.removeTabBarBadge({
        index: 3
      })
    }
  },
  handInput(e) {
    this.setData({
      mesValue: e.detail.value.trim()
    })
    if (e.detail.value.trim() != '') {
      this.setData({
        mn1: false
      })
    } else if(this.data.imglist.length <= 0) {
      this.setData({
        mn1: true
      })
    }
  },

  // 选择
  handShow() {
    this.setData({
      isShow: true
    })
  },
  handXuan(e) {
    const { qtype } = e.currentTarget.dataset
    this.setData({
      qtype,
      isShow: false
    })
  },
  bindCasPickerChange(e) {
    getApp().globalData.qtype = e.detail.value
    this.setData({
      qtype: e.detail.value
    })
  },
  // 发送
  jiance() {
    const userInfo = wx.getStorageSync('userInfo')
    const sts = userInfo.avatarUrl.split('/')
    let uheadpic = ''
    sts.forEach((value) => {
      if (uheadpic === '') {
        uheadpic = value
      } else {
        uheadpic += `xd728${value}`
      }
    })
    if (this.data.mesValue == '' && this.data.imglist.length <= 0) {
      wx.showToast({
        title: '请输入内容',
        icon: 'error',
        duration: 1500
      })
      return
    }
    const reg=/^(([a-z]+[0-9]+)|([0-9]+[a-z]+))[a-z0-9]*$/i
    if (reg.test(this.data.mesValue)) {
      wx.showToast({
        title: '请不要随意测试!',
        icon: 'error',
        duration: 1500
      })
      return
    }
    if (!isNaN(this.data.mesValue)) {
      wx.showToast({
        title: '请不要随意测试!',
        icon: 'error',
        duration: 1500
      })
      return
    }
    const testall = /^[a-zA-Z]+$/
    if (testall.test(this.data.mesValue)) {
      wx.showToast({
        title: '请不要随意测试!',
        icon: 'error',
        duration: 1500
      })
      return
    }
    const content = {
      id: +new Date(),
      userid: this.data.userId,
      uname: userInfo.nickName,
      uheadpic,
      content: this.data.mesValue,
      usex: userInfo.gender,
      ctime: formatTime(new Date()),
      imgPath: '',
      status: 1,
      giftNum: 0,
      likeNum: 0,
      viewNum: 0
    }
    // 无用表单参数，但暂时不能删
    let fields = [
      { name: 'name', value: '253' },
      { name: 'number', value: '46374' }
    ]
    let files = this.data.imglist

    files = files.map((item, index) => {
      return { name: 'imgs', filePath: item }
    })
    wx.showLoading({
      title: '上传中',
      mask: true
    })
      
    new Multipart({
      files,
      fields
    })
      .submit(
        `https://xxxx/xxxx/${JSON.stringify(content)}/${
          this.data.qtype
        }/${this.data.imglist.length}`
      )
      .then(({ data }) => {
        wx.hideLoading()
        if (data.state === 1) {
          const { qtype } = this.data
          this.setData({
            imglist: [],
            mesValue: '',
            qtype: 0
          })
          wx.showToast({
            title: '发布成功',
            icon: 'success',
            duration: 2000,
            success: () => {
              wx.navigateTo({
                url: '/pages/qiang/qiang?type='+qtype
              })
            }
          })
        } else {
          wx.showToast({
            title: '上传失败',
            icon: 'error',
            duration: 2000
          })
        }
      })
      .catch((err) => {
        wx.hideLoading()
        if (err.errMsg == 'request:fail timeout') {
          wx.showModal({
            title: '提示',
            content: '上传超时了!',
            showCancel: false,
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '网络出错!',
            showCancel: false
          })
        }
      })
  }
})
